(function($){
	//定义全局变量
	var win = window;
	var doc = document;
	var util = win.util = {};
	var server = win.server = {};
	var handler = win.handler = {};
	var strategyId=20;
	//富文本编辑器
	var editor;
	util.textEditor=function(){
		KindEditor.ready(function(K) {
	        editor = K.create($("#innerContent"), {
	            resizeType : 1,
	            width  : "100%" ,
	            height :"410px" ,
	            allowPreviewEmoticons : false,
	            allowImageUpload : false,
	            items : [
	                'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
	                'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
	                'insertunorderedlist', '|', 'emoticons', 'image', 'link']
	        });
	    });
	}
   
	//多个图片的上传
	server.strategyFile=function(){

			var sellerBaseImage = $("#sellerBaseImage");
			sellerBaseImage.empty();
			
	  		//var uploadButton = $("<a id='sellerBaseImage_button' href=''></a>").text("商家图片上传").appendTo(sellerBaseImage) ;

			
			$('.editor').prepend('<h2 class="upload-butt">上传图片</h2>');

			var uploadButton = $('.editor').prepend('<h2 id="sellerBaseImage_button">选择图片</h2>');
			var doUploadButt = $(".upload-butt") ;
			
	  		var sellerBaseImageUploader = new plupload.Uploader({
			    browse_button: "sellerBaseImage" + "_button" ,
			    url:"/jybb-upload/image/upload.do?belongId=0&imageCatalog=f1" 
			}) ;
	  		
	  		sellerBaseImageUploader.init() ;
			
	  		
	  		sellerBaseImageUploader.bind('FilesAdded', function(up, files) {

			    plupload.each(files, function(file) {
			       // var li = $("<li></li>").attr("id",file.id).text(file.name + plupload.formatSize(file.size));
			        /*var delSpan = $("<span>X</span>").appendTo(li).on("click",function(){
			        }) ;*/
			        //$('.editor').prepend(li);
			    });
			    
			});
	  		
	  		sellerBaseImageUploader.bind('FileUploaded', function(up, file,result) {
	  			
	  			var fileId = eval(result.response)[0]
	  			$.ajax({
				 	url :"/jybb-upload/image/getImgById.json?imageId=" +fileId ,
				   	type : "GET" ,
				    dataType: "json" ,
				    success:function(data){
				    	var images = null ;
				    	//alert(1);
				    	console.log(data);
				    	if("200" === data["code"]){
				    		image = data["result"] ;
			    			var html= editor.html();
							editor.html(html+"</br><img src='"+image["imageUrl"]+"' style='display:block;width:500px;height:500px;'/></br>");
				    	}
				    } ,
			        error:function(){
			        	alert("图片列表获取失败!") ;
			        }
		 		}) ;
	  		
	  		});
	  		
	  		sellerBaseImageUploader.bind('Error', function(up,err) {
			    alert("文件上传发生错误，请重试!") ;
			});
	  		
	  		uploadButton.on("click",function(){
				
				doUploadButt.on("click",function(){
					sellerBaseImageUploader.start() ;
					$(this).unbind("click") ;
				}) ;
			
			}) ;
		
  
	};

	//单个图片的上传
	/*server.ajaxFileUpload=function () {
		*//*var xmlHttpRequest = new XMLHttpRequest();
		var genId = "UPLOAD_" + new Date().getTime();
		var file = document.getElementById("selectSingle");
		//uploadNum = index;
		var formData = new FormData();
		formData.append(genId, file.files[0]);
		xmlHttpRequest.open("POST", "http://localhost:8070/jybb-upload/image/upload.do?belongId="+strategyId+"&imageCatalog=f16", true);
		xmlHttpRequest.send(formData);
		xmlHttpRequest.onreadystatechange = function () {
			if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
				//var ids = JSON.parse(xmlHttpRequest.responseText);
				//document.getElementById("picUrl" + index).value = ids[0];
				alert('图片上传成功');
			}
		}*//*

		window.setTimeout(function(){
			$.ajaxFileUpload({
				url: "http://localhost:8070/jybb-upload/image/upload.do?belongId="+strategyId+"&imageCatalog=f16", //用于文件上传的服务器端请求地址
				secureuri: false, //是否需要安全协议，一般设置为false
				fileElementId: 'selectSingle', //文件上传域的ID
				dataType: 'json', //返回值类型 一般设置为json
				success: function (data, status)  //服务器成功响应处理函数
				{
					$("#singleImg").attr("src", data.imgurl);

					if (typeof (data.error) != 'undefined') {
						if (data.error != '') {
							alert(data.error);
						} else {
							alert(data.msg);
						}
					}
					console.log(data);
				},
				error: function (data, status, e)//服务器响应失败处理函数
				{
					alert('错误');
				}
			})
		},1000)
    }*/
    //删除图片
    /*server.removeSingleImg=function(){
    	$.ajax({
		 	url : cms.baseUrl + "/jybb-upload/image/delete.json?imageId=",
		   	type : "GET" ,
		    dataType: "json" ,
		    success:function(data){
		    	
		    } ,
		    error:function(){
		    	alert("图片删除失败!") ;
		    }
		}) ;
    }*/

	//判断商品头图存不存在
    util.isSingleImg=function(){
    	if($('#singleImg').attr('src')==""){
	    	$('#selectSingle,#uploadSingle').show();
	    	$('#removeSingle').hide();
	    }else{
	    	$('#selectSingle,#uploadSingle').hide();
	    	$('#removeSingle').show();
	    }
    }

    handler.changeTag=function(){
    	$('#choose span').on('click',function(){
    		var _that=$(this);
    		var flag=0;
			$('#selecteds span').each(function(i,list){
    			if(parseInt($(this).attr('goodsTag'))==parseInt(_that.attr('goodsTag'))){
    				++flag;
    			}
    		})
			if(flag==0){
				$(this).clone().appendTo('#selecteds');
    			$(this).addClass('grey');
			}
    	})

    	$('#selecteds').delegate('span','click',function(){
    		var _that=$(this);
    		$('#choose span').each(function(i,list){
    			if(parseInt($(this).attr('goodsTag'))==parseInt(_that.attr('goodsTag'))){
    				_that.remove();
    				$(this).removeClass('grey').addClass('yellow');
    			}
    		})
    	})

    }

})(jQuery)

$(function(){

	window.server.strategyFile()

	$("#uploadSingle").on('click',function () {
        server.ajaxFileUpload();
    })

	$('#removeSingle').on('click',function(){
		server.removeSingleImg();
	});
	window.util.isSingleImg();
	window.handler.changeTag();

	window.util.textEditor()


})


function upload() {
    var xmlHttpRequest = new XMLHttpRequest();
    var genId = "UPLOAD_" + new Date().getTime();
    var file = document.getElementById("fileupload1111");
    var formData = new FormData();
    formData.append(genId, file.files[0]);
    xmlHttpRequest.open("POST","/jybb-upload/image/upload.do?belongId=0&imageCatalog=f16", true);
    xmlHttpRequest.send(formData);
    xmlHttpRequest.onreadystatechange = function () {
        if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
            var id = JSON.parse(xmlHttpRequest.responseText);

			$.ajax({
				url :"/jybb-upload/image/getImgById.json?imageId=" +id ,
				type : "GET" ,
				dataType: "json" ,
				success:function(data){
					var images = null ;

					console.log(data);
					if("200" === data["code"]){
						var image = data["result"] ;

						$("#singleImg").attr("src",image["imageUrl"]);
					}
				} ,
				error:function(){
					alert("图片列表获取失败!") ;
				}
			}) ;

            alert('图片上传成功');
        }
    }
}


/*
var xmlHttpRequest = new XMLHttpRequest();
var genId = "UPLOAD_" + new Date().getTime();
var file = document.getElementById("selectSingle");
//uploadNum = index;
var formData = new FormData();
formData.append(genId, file.files[0]);
xmlHttpRequest.open("POST", "http://localhost:8070/jybb-upload/image/upload.do?belongId="+strategyId+"&imageCatalog=f16", true);
xmlHttpRequest.send(formData);
xmlHttpRequest.onreadystatechange = function () {
	if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
		/ar ids = JSON.parse(xmlHttpRequest.responseText);
		//document.getElementById("picUrl" + index).value = ids[0];
		alert('图片上传成功');
	}
}
*/